import base64

def file_to_base64(file_path):
    with open(file_path, 'rb') as f:  # 以二进制读模式打开文件
        file_bytes = f.read()  # 读取文件字节流
        base64_bytes = base64.b64encode(file_bytes)  # 编码
        return base64_bytes.decode('utf-8')  # 转为字符串

# 示例：编码一张图片
fn = input("fn: ")
fnn = input("function name: ")
image_base64 = file_to_base64(input(f"please input a file to generate blob(will create file {fn}):"))
# print("文件的 Base64 编码：" + image_base64)

with open(fn, "w", encoding="utf-8") as f:
    f.write(f"""function {fnn + "base64ToBlob"}(base64Str, mimeType = 'application/octet-stream') {{
  const base64Data = base64Str.replace(/^data:.*;base64,/, '');
  const binaryStr = atob(base64Data);
  const len = binaryStr.length;
  const uint8Array = new Uint8Array(len);
  for (let i = 0; i < len; i++) {{
    uint8Array[i] = binaryStr.charCodeAt(i);
  }}
  return new Blob([uint8Array], {{ type: mimeType }});
}}
function {fnn}() {{
            const imgBase64 = "{image_base64}";
// 转换为 Blob（自动识别 MIME 类型，或手动指定）
const imgBlob = base64ToBlob(imgBase64);

// 生成 Blob URL 并在 img 标签中显示
const blobUrl = URL.createObjectURL(imgBlob, "data:application/java-archive");
// 用完后释放 Blob URL（避免内存泄漏）
//   URL.revokeObjectURL(blobUrl);
return blobUrl;
            }}""")
